<?php
/**
 *$path 上传文件保存路径
 *return array 
 *["error"] false ["info"] 存放失败原因或成功的文件名
 */
function uploadFile($filename, $path, $typelist = null)
{
    $upfile = $_FILES[$filename];
    if (empty($typelist))
    {
        //允许的图片类型
        $typelist = array("image/gif", "image/jpeg", "image/jpg", "image/png");
    } 
    //存放返回的结果
    $res = array("error" => false);
    if ($upfile["error"] > 0)
    {
        switch ($upfile["error"])
        {
        case 1:
            $res["info"] = "上传的图片超过了php.ini中的upload_max_filesize限制！";
            break;
        case 2:
            $res["info"] = "上传图片大小超过了HTML表单中的upload_max_filesize的限制！";
            break;
        case 3:
            $res["info"] = "文件部分被上传！";
            break;
        case 4:
            $res["info"] = "文件没有被上传！";
            break;
        case 6:
            $res["info"] = "找不到临时文件夹！";
            break;
        case 7:
            $res["info"] = "文件写入失败！";
            break;
        default:
            $res["info"] = "未知错误！";
            break;
        }
        return $res;
    }
    
    if ($upfile["size"] > 500000)
    {
        $res["info"] = "文件上传过大！";
        return $res;
    }

    if (!in_array($upfile["type"], $typelist))
    {
        $res["info"] = "文件的上传类型不对！";
        return $res;
    }

    //初始化图片信息
    $fileinfo = pathinfo($upfile["name"]);
    do
    {
        //随机产生一个图片的名字
        $newfile = date("YmdHis").rand(1000, 9999).".".$fileinfo["extension"];
    }while(file_exists($newfile));
    
    if (is_uploaded_file($upfile["tmp_name"]))
    {
        if (move_uploaded_file($upfile["tmp_name"], $path."/".$newfile))
        {
            $res["info"] = $newfile;
            $res["error"] = true;
            return $res;
        }
        else
        {
            $res["info"] = "文件上传失败！";
        }
    }
    else
    {
        $res["info"] = "不是一个上传的文件！";
    }

    return $res;
}

/*
*检查相应的值是否为空，是否符合输入类型
*/
function checkValidate($must_inter, $not_emp, $price)
{
    $res = array("error" => true);
    $flag = true;
    
    //检查是否有空值*/
    foreach($must_inter as $key => $value)
    {
        for ( $j = 0; $j < count($value); $j++ )
        {
            if ( empty($value[$j]) )
            {
                $flag = false;
                break;
                
            }
        }
        if (!$flag)
        {
            break;
        }
    }

    foreach ($not_emp as $value)
    {
        if (empty($value))
        {
            $flag = false;
            break;
        }
    }

    //检查输入是否符合要求
    if ($flag)
    {
        foreach ($must_inter as $key => $arr)
        {
            foreach($arr as $value)
            {
                $pattern = "/^\d+$/";
                if (!preg_match($pattern, $value))
                {
                    $res["error"] = false;
                    $res["info"] = $key."这一行未正确输入!";
                    return $res;
                }     
            }
        }

        if (!is_numeric($price))
        {
            $res["error"] = false;
            $res["info"] = "商品价钱这一行未正确输入！";
            return $res;
        }   
    }
    else
    {
        $res["error"] = false;
        $res["info"] = "你的输入中有空值！";
    }  

    return $res; 
}

/*
*等比缩放函数
*string $picname 被缩放的处理图片源
*int $maxX 缩放后图片的最大宽度
*int $maxY 缩放后图片的最大高度
*string $pre 缩放后图片的前缀名
*返回后的图片名称 return string 返回后的图片名称(带路径)，如：a.jpg => s_a.jpg
*/
function imageUpdateSize($picname, $maxX = 200, $maxY = 200, $pre = "s_")
{
    $info = getimagesize($picname);  //或取图片信息
    /*
    echo "<pre>";
    print_r($info);
    echo "</pre>";
*/
    $width = $info[0];  //图片的宽度
    $height = $info[1];  //图片的高度

    switch ($info[2]) 
    {
        case 1: //gif
            $img = imagecreatefromgif($picname); //获取原图的图像资源
            break;
        case 2: //jpg
            $img = imagecreatefromjpeg($picname);
            break;
        case 3:   //png
            $img = imagecreatefrompng($picname);
            break;
        default:
            die("图片类型错误！");
            break;
    }
    //计算缩放比例
    if ( ($maxX / $width) > ($maxY / $height) )  //原图的宽比高要大
    {
        $rate = $maxY / $height;
    }
    else
    {
        $rate = $maxX / $width;
    }
    $newW = floor($rate * $width);
    $newH = floor($rate * $height);

    //创建一个新的图像源
    $newImg = imagecreatetruecolor($newW, $newH);
    //执行等比缩放
    imagecopyresampled($newImg, $img, 0, 0, 0, 0, $newW, $newH, $width, $height);
    
    //根据图片类型，输出相应格式的图片
    $picinfo = pathinfo($picname);
    $newPicname = $picinfo["dirname"]."/".$pre.$picinfo["basename"];
    switch ($info[2]) 
    {
         case 1: //gif
            imagegif($newImg, $newPicname); 
            break;
        case 2: //jpg
           imagejpeg($newImg, $newPicname); 
            break;
        case 3:   //png
          imagepng($newImg, $newPicname); 
            break;
    }

    //释放图片资源
    imagedestroy($img);
    imagedestroy($newImg);
    //返回新的文件名
    return $newPicname;

}

function filterSearchWords($searchQuery, $userSearch)
{
    $whereList = array();

    //过滤用户中输入的  ','
    $cleanSearch = str_replace(',', ' ', $userSearch);
    $searchWords = explode(' ', $cleanSearch);   //将字符串分割为数组

    if (count($searchWords) > 0)
    {
       foreach($searchWords as $word)
       {
          if (!empty($word))
          {
             $whereList[] = "name like '%$word%'";
          }  
       }
    }
   $whereClause = implode(" or ", $whereList);   //将数组转换为字符串
   if (!empty($whereClause))
   {
       $searchQuery .= " where $whereClause";
   }
   return $searchQuery." order by addtime desc";
}


/*
对从数据库获取的信息进行截取，让在browser换行显示
$str, 目标字符串，
$length, 每一行目标字串的长度
*/
function getLimitString($str, $length)
{
    $arr = array();
    preg_match_all('/./us', $str, $match);
    $rows = ceil(count($match[0]) / $length);
    for ($i = 0; $i < $rows; $i++)
    {
        $arr[$i] = iconv_substr($str, $i*$length, $length, "utf-8");
    }
    $array = implode("<br />", $arr);
    return $array;
}
?>
